package com.arrogames.blondbattle.music 
{
	import com.greensock.TweenLite;
	import flash.events.Event;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundTransform;
	
	/**
	 * ...
	 * @author Robin van den Bogaard
	 */
	public class BBAudio {
		
		private var sound:Sound;
		private var channel:SoundChannel;
		
		private var _volume:Number;
		
		private var loop:Boolean;
		private var fade:Boolean;
		
		private var fadeIn:TweenLite;
		private var fadeOut:TweenLite;
		
		private var muted:Boolean;
		
		public function BBAudio(sound:Sound, loop:Boolean=false, fade:Boolean = false, volume:Number=1.0) {
			this.sound = sound;
			this.muted = false;
			this.volume = volume;
			this.fade = fade;
			this.loop = loop;
		}
		
		public function play():BBAudio {
			if (fade) {
				volume = 0;
				var targetVolume:Number = muted ? 0 : 1.0;
				fadeIn = TweenLite.to(this, 2, { volume:targetVolume } );
			} 
			__play();
			return this;
		}
		
		private function __play():void {
			channel = sound.play();
			channel.soundTransform = new SoundTransform(volume);
			if (loop) {
				channel.addEventListener(Event.SOUND_COMPLETE, onComplete);
			}
		}
		
		public function stop():void {
			if (loop) {
				channel.removeEventListener(Event.SOUND_COMPLETE, onComplete);
			}
			if (fade && !muted) {
				fadeOut = TweenLite.to(this, 2, { volume:0, onComplete:__stop } );
			} else {
				__stop();
			}
		}
		
		public function __stop():void {
			channel.stop();
		}
		
		private function onComplete(event:Event):void {
			channel.removeEventListener(event.type, onComplete);
			__play();
		}
		
		public function mute():void {
			TweenLite.killTweensOf(this);
			TweenLite.to(this, 2, { volume:0 } );
			muted = true;
		}
		
		public function unmute():void {
			TweenLite.killTweensOf(this);
			volume = 0;
			TweenLite.to(this, 2, { volume:1.0 } );
			muted = false;
		}
		
		public function get volume():Number {
			return _volume;
		}
		
		public function set volume(value:Number):void {
			_volume = value;
			if (channel != null) {
				channel.soundTransform = new SoundTransform(_volume);
			}
		}
		
	}

}